import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { OperationType } from './entities/operation-type.entity';
import { CreateOperationTypeDto } from './dto/create-operation-type.dto';
import { UpdateOperationTypeDto } from './dto/update-operation-type.dto';

@Injectable()
export class OperationTypesService {
  constructor(
    @InjectRepository(OperationType)
    private readonly operationTypeRepository: Repository<OperationType>,
  ) {}

  async create(createOperationTypeDto: CreateOperationTypeDto): Promise<OperationType> {
    const operationType = this.operationTypeRepository.create(createOperationTypeDto);
    return await this.operationTypeRepository.save(operationType);
  }

  async findAll(): Promise<OperationType[]> {
    return await this.operationTypeRepository.find({
      order: { id: 'ASC' },
    });
  }

  async findOne(id: number): Promise<OperationType> {
    const operationType = await this.operationTypeRepository.findOne({ where: { id } });
    if (!operationType) {
      throw new NotFoundException(`操作类型 ID ${id} 不存在`);
    }
    return operationType;
  }

  async update(id: number, updateOperationTypeDto: UpdateOperationTypeDto): Promise<OperationType> {
    const operationType = await this.findOne(id);
    Object.assign(operationType, updateOperationTypeDto);
    return await this.operationTypeRepository.save(operationType);
  }

  async remove(id: number): Promise<void> {
    const operationType = await this.findOne(id);
    await this.operationTypeRepository.remove(operationType);
  }

  async deactivate(id: number): Promise<OperationType> {
    const operationType = await this.findOne(id);
    operationType.isActive = false;
    return await this.operationTypeRepository.save(operationType);
  }

  async activate(id: number): Promise<OperationType> {
    const operationType = await this.findOne(id);
    operationType.isActive = true;
    return await this.operationTypeRepository.save(operationType);
  }
}